package cn.lizheng.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.lizheng.dao.UserDao;
import cn.lizheng.pojo.User;


/**
 * @author WANGZIC
 * @description 登录请求处理类
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //接收表单信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //设置回显
        request.setAttribute("username", username);
        request.setAttribute("password", password);


        //根据用户名查询用户
        User user = new UserDao().selectByUsername(username);
        if (user != null) {
            if (user.getPassword().equals(password)) {
                //session存储
//				HttpSession session=request.getSession();
//				session.setAttribute("loginuser",user);
                request.getSession().setAttribute("user", user);
                response.sendRedirect("index.jsp");
            } else {
                request.setAttribute("loginError", "* 密码错误");
                request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("loginError", "* 用户不存在");
            request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}
